
#include <stdio.h>
#include <stdint.h>
#include <sys/time.h>

void UtilDelayUs(uint32_t us)
{
    struct timeval delay;
    delay.tv_sec = us / 1000000;
    delay.tv_usec = us % 1000000;
    select(0, NULL, NULL, NULL, &delay);
}

void UtilDelayMs(uint32_t ms)
{
    UtilDelayUs(ms * 1000);
}

uint32_t UtilGetTickUs(void)
{
    struct timeval tv = {0};
    gettimeofday(&tv, NULL);
    return (uint32_t)(tv.tv_sec * 1000000u + tv.tv_usec);
}

uint32_t UtilGetTickMs(void)
{
    struct timeval tv = {0};
    gettimeofday(&tv, NULL);
    return (uint32_t)(tv.tv_sec * 1000u + tv.tv_usec / 1000);
}

const char* UtilGetTimeStampHHMMSS(void)
{
    static char timeStr[3][16] = {0}; //增大数值3可提升多线程支持能力
    static uint32_t index = 0;
    int32_t tick = (index++) % 3; //简单排队

    struct timeval tv = {0};
    gettimeofday(&tv, NULL);
    snprintf(timeStr[tick], 16,
            "%02ld:%02ld:%02ld",
            (tv.tv_sec % 86400 / 3600 + 8) % 24,
            tv.tv_sec % 3600 / 60,
            tv.tv_sec % 60);
    return timeStr[tick];
}

const char* UtilGetTimeStampSSMMMUUU(void)
{
    static char timeStr[3][16] = {0};
    static uint32_t index = 0;
    int32_t tick = (index++) % 3;

    struct timeval tv = {0};
    gettimeofday(&tv, NULL);
    snprintf(timeStr[tick], 16,
            "%02ld:%03ld:%03ld",
            tv.tv_sec % 60,
            tv.tv_usec / 1000,
            tv.tv_usec % 1000);
    return timeStr[tick];
}
